<template>
  <!-- 单位专业管理 -->
  <div class="app-container">
        <!-- 搜索 -->
        <searchForm
          :formOptions="formOptions"
          @onSearch="onSearch"
          @onReset="onReset"
          :formLabelWidth="formLabelWidth"
          v-show="showSearch"
        />
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basic:speciality:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['basic:speciality:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basic:speciality:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="name" :show-overflow-tooltip="true" label="专业名称" width="200" align="center"></el-table-column>
          <el-table-column prop="sCode" label="专业代码" align="center"></el-table-column>
          <el-table-column prop="nickName" label="专业简称" align="center"></el-table-column>
          <el-table-column
            prop="deptName"
            :show-overflow-tooltip="true"
            label="所属院系"
            align="center"
            width="220"
          ></el-table-column>
          <el-table-column prop="markCode" label="被标专业代码" align="center" width="100"></el-table-column>
          <el-table-column prop="sType" label="学制" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.bc_speciality_type" :value="scope.row.sType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="专业状态" align="center">
            <template slot-scope="scope">  
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column prop="specialitySize" label="专业人数" align="center">
          </el-table-column>
          <el-table-column prop="remark" label="类型" :show-overflow-tooltip="true" align="center"></el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basic:speciality:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basic:speciality:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
 

    <!-- 专业列表添加或修改 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="60%"
      append-to-body
      @close="$refs['form'].resetFields()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属院系" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择" clearable class="elSelect" @change="handleChange" style="width: 100%">
                <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                  :value="item.deptId"></el-option>
              </el-select>
              <!-- <el-cascader
                clearable
                ref="cascaderAddr"
                v-model="form.deptId"
                :options="deptOptions"
                style="width: 100%"
                :props="{value: 'id',currentLabels: 'label',children: 'children',checkStrictly: true}"
                @change="handleChange"
              ></el-cascader> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入专业名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业代码" prop="sCode">
              <el-input v-model="form.sCode" placeholder="请输入专业代码" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业简称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入专业简称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位代码" prop="unitCode">
              <el-input v-model="form.unitCode" placeholder="请输入单位代码" disabled maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被标专业代码" prop="markCode">
              <el-input v-model="form.markCode" placeholder="请输入被标注专业代码" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学制" prop="sType">
              <el-select v-model="form.sType" placeholder="请选择学制" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.bc_speciality_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="remark">
              <el-select v-model="form.remark" placeholder="请选择" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.basic_speciality_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入" maxlength="200" />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加左侧单位树或修改 -->
    <!-- <el-dialog
      :title="title"
      :visible.sync="deptVisible"
      width="40%"
      append-to-body
      @close="$refs['formdept'].resetFields()"
    >
      <el-form ref="formdept" :model="deptFrom" :rules="deptRules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="上级单位" prop="parentId">
              <el-cascader
              ref="deptTree"
                v-model="deptFrom.parentId"
                :options="deptOptions"
                :props="{ checkStrictly: true ,value: 'id',currentLabels: 'label'}"
                style="width: 100%"
                @change="deptTree"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="单位名称" prop="deptName">
              <el-input v-model="deptFrom.deptName" placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="单位代码" prop="dwdm">
              <el-input placeholder="请输入单位代码" v-model="deptFrom.dwdm" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="是否使用" prop="status">
              <el-select v-model="deptFrom.status" placeholder="请选择" clearable style="width: 100%">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDept">确 定</el-button>
        <el-button @click="deptVisible = false">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
import searchForm from "@/components/Search/searchForm.vue";
import treeIndex from "@/components/tree/index.vue";
import { addDept, updateDept, getDept, delDept } from "@/api/system/dept";
import {
  specialityList,
  getSpecialityByDeptId,
  speciality,
  specialityInfor,
  updataSpeciality,
  delSpeciality
} from "@/api/information/unitMajor";
import {
  collegeSelect
} from "@/api/information/studentInfor"
import { getDicts } from "@/api/system/dict/type";
import { deptTreeSelect } from "@/api/system/user";
export default {
  components: { searchForm, treeIndex },
  dicts: [
    "sys_normal_disable", // 是否使用
    "basic_speciality_type", // 专业类型
    "bc_speciality_type" // 学制
  ],

  data() {
    return {
      showSearch: true,
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      formLabelWidth: "110px",
      formOptions: [
        {
          label: "所属院系",
          prop: "deptId",
          element: "el-select",
          options: [],
          placeholder: "请输入专业名称"
        },
        {
          label: "专业名称",
          prop: "name",
          element: "el-input",
          placeholder: "请输入专业名称"
        },
        {
          label: "专业代码",
          prop: "sCode",
          element: "el-input",
          placeholder: "请输入专业代码"
        },
        {
          label: "被标注专业代码",
          prop: "markCode",
          element: "el-input",
          placeholder: "请输入被标注专业代码"
        },
        {
          label: "学制",
          prop: "sType",
          element: "el-select",
          options: [],
          placeholder: "请选择学制"
        },
        {
          label: "专业状态",
          prop: "status",
          element: "el-select",
          options: [],
          placeholder: "请选择业状态"
        },
        {
          label: "类型",
          prop: "remark",
          element: "el-select",
          options: [],
          placeholder: "请选择类型"
        },
      ],
      options: [],
      deptForm: {},

      tableData: [],
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "请选择所属单位", trigger: "change" }
        ],
        name: [
          { required: true, message: "专业名称不能为空", trigger: "blur" }
        ],
        sCode: [
          { required: true, message: "专业代码不能为空", trigger: "blur" }
        ],
        nickName: [{ required: false, trigger: "blur" }],
        unitCode: [
          { required: true, message: "单位代码不能为空", trigger: "blur" }
        ],
        markCode: [{ required: false, trigger: "blur" }],
        sType: [{ required: true, message: "请选择学制", trigger: "change" }],
        status: [
          { required: true, message: "请选择是否使用", trigger: "change" }
        ],
        remark: [{ required: true, message: "请选择类型", trigger: "change" }]
      },
      deptRules: {
        parentId: [
          { required: true, message: "请选择所属单位", trigger: "change" }
        ],
        deptName: [
          { required: true, message: "专业名称不能为空", trigger: "blur" }
        ],
        dwdm: [
          { required: true, message: "专业代码不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择是否使用", trigger: "change" }
        ]
      },
      deptNameId: "",
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: ""
      },
      title: "",
      // 修改或添加弹窗
      open: false,
      form: {
        name: "",
        sCode: "",
        nickName: "",
        unitCode: "",
        markCode: "",
        sType: "",
        status: "",
        remark: "",
        deptId: ""
      },
      deptFrom: {},
      deptVisible: false,
      ids: [],
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      name: [],
      deptId: undefined,
      deptNameTree: ""
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptNameId(val) {
      console.log(val);
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDeptTree();
    getDicts("basic_speciality_type").then(res => {
      this.formOptions[6].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
    getDicts("bc_speciality_type").then(res => {
      this.formOptions[4].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
    getDicts("sys_normal_disable").then(res => {
      this.formOptions[5].options = res.data.map(item => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"]
        };
      });
    });
  },
  methods: {
     treeBtnClick(type) {
      switch (type) {
        case 'add':
          this.deptAdd()
          break;
        case 'edit':
          this.deptEdit()
          break;
        case 'del':
          this.deptDelete()
          break;
      }
     },
     // 获取搜索表单提交的数据
     onSearch(val) {
      // 查询条件和分页数据合并
      this.queryParams = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      this.queryParams.deptId = ''
      this.queryParams = Object.assign(this.queryParams, data);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.form = {};
    },
    handleChange(value) {
      console.log(this.deptOptions,value,'fd1')
      var obj = {}
      obj= this.deptOptions.find(function(i){
        return i.deptId === value
      });
      this.form.unitCode = obj.dwdm
      console.log(obj,'fd')
      // let nodesObj = this.$refs["cascaderAddr"].getCheckedNodes();
      // nodesObj.forEach(item => {
      //   // console.log(item.data.unitCode,1231)
      //   this.form.unitCode = item.data.unitCode;
      // });
      
      // this.form.multistage = value + "";
    },
    deptTree(value) {
      // let nodesObj = this.$refs["deptTree"].getCheckedNodes();
      // nodesObj.forEach(item => {
      //   // console.log(item.data.unitCode,1231)
      //   this.deptFrom.dwdm = item.data.unitCode;
      // });
      if (value) {
        this.deptFrom.parentId = value[value.length - 1];
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 修改部门按钮
    deptEdit() {
      if (this.deptId) {
        this.deptVisible = true;
        getDept(this.deptId).then(res => {
          this.deptFrom = res.data;
          this.deptFrom.parentId = this.deptFrom.deptId
        });
      } else {
        this.$modal.msgWarning("请选择需要修改的部门");
      }
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      specialityList(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.loading = false;
        this.total = response.total;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.name = selection.map(item => item.name);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      collegeSelect().then(response => {
        
        this.deptOptions = response.data;
        this.formOptions[0].options = this.deptOptions.map(item => {
        return {
          value: item["deptId"],
          label: item["deptName"]
        };
      });
        // this.queryParams.deptId = response.data[0].id;
        this.getList();
      });
    },
    // tree树形选中的值
    handleNodeClick(data) {
      this.deptId = data.id;
      this.deptNameTree = data.label;
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 添加部门
    deptAdd() {
      this.deptForm = {};
      this.deptVisible = true;
      this.title = "添加部门";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.open = true;
      this.title = "添加专业列表";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id || this.ids;
      this.name = row.name || this.name;
      this.$modal
        .confirm('是否确认删除专业名称"' + this.name + '"的数据项？')
        .then(function() {
          return delSpeciality(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 删除部门按钮操作 */
    deptDelete() {
      if (this.deptId) {
        this.$modal
        .confirm('是否确认删除专业"' + this.deptNameTree + '"的数据项？')
        .then(() => {
          delDept(this.deptId).then(() => {
            this.getDeptTree();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
      } else {
        this.$modal.msgWarning("请选择需要删除的部门");
      }
     
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const roleId = row.id || this.ids;
      specialityInfor(roleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改专业列表";
      });
    },
    // 提交新增或修改的数据
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updataSpeciality(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            speciality(this.form).then(response => {
              console.log(response, "新增成功");
              this.$modal.msgSuccess("新增成功");
              this.form = {};
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 部门添加修改
    submitFormDept: function() {
      console.log(this.deptForm);
      this.$refs["formdept"].validate(valid => {
        if (valid) {
          if (this.deptId != undefined) {
            const { deptId, parentId, deptName, dwdm, status } = this.deptFrom;
            updateDept({
              parentId,
              deptName,
              dwdm,
              status,
              deptId
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.deptVisible = false;
              this.deptForm = {};
              this.getDeptTree();
            });
          } else {
            const { parentId, deptName, dwdm, status } = this.deptFrom;
            addDept({
              parentId,
              deptName,
              dwdm,
              status
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.deptForm = {};
              this.deptVisible = false;
              this.getDeptTree();
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.head-container {
  overflow-x: scroll;
}
</style>